<?php

namespace App\Http\Controllers\Admin\Setting\Wechat;

use App\Http\Controllers\Admin\Controller;
use App\Repositories\WechatMaterialRepository;
use App\Services\WeChatOfficialAccountService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Inertia\Response;

class WeChatMaterialController extends Controller
{
    protected array $validateMessages = [
        'name.*' => '请输入素材名称',
        'type.*' => '请输入素材类型',
        'media_id.*' => '请输入素材id',
        'status.*' => '请输入正确的状态',
        'sort.*' => '请输入排序',
    ];

    public function __construct(Request $request, WechatMaterialRepository $repository)
    {
        $this->request = $request;
        $this->repository = $repository;
    }

    public function index(): Response
    {
        $list = $this->repository->getList();

        return $this->inertia('wechat/material/index', [
            'data' => $list->items(),
            'pagination' => [
                'total' => $list->total(),
                'page' => $list->currentPage(),
                'pageSize' => $list->perPage(),
            ],
        ]);
    }

    public function upload(WeChatOfficialAccountService $weChatOfficialAccountService): array
    {
        $file = $this->request->file('file');
        $path = sprintf('images/%s', date('Ymd'));
        $path = $file->store($path, ['disk' => 'public']);
        $url = asset('storage/'.$path);
        $content = Storage::disk('public')->get($path);

        $api = $weChatOfficialAccountService->getClient();
        $response = $api->withFileContents($content, 'media')->post('cgi-bin/material/add_material?type=image');
        $result = $response->toArray(true);
        $this->repository->create([
            'name' => $file->getClientOriginalName(),
            'type' => 'image',
            'media_id' => $result['media_id'],
            'url' => $url,
            'content' => [
                'media_id' => $result['media_id'],
                'url' => $result['url'],
            ],
        ]);

        return [
            'data' => [
                'url' => asset('storage/'.$path),
                'media_id' => $result['media_id'],
                'media_url' => $result['url'],
            ],
            'code' => 200,
        ];
    }

    public function store(WeChatOfficialAccountService $weChatOfficialAccountService)
    {
        $params = $this->validate(
            $this->request,
            [
                'name' => 'nullable|string',
                'type' => 'required|string',
                'file' => 'nullable|string',
            ],
            $this->validateMessages
        );
        $path = explode('http://127.0.0.1:8000/storage/', $params['file'])[1];
        $content = Storage::disk('public')->get($path);

        $api = $weChatOfficialAccountService->getClient();
        $response = $api->withFileContents($content, 'media')->post('cgi-bin/material/add_material?type='.$params['type']);
        $result = $response->toArray(true);
        $this->repository->create([
            'name' => $params['name'],
            'type' => $params['type'],
            'media_id' => $result['media_id'],
            'url' => $params['file'],
            'content' => [
                'media_id' => $result['media_id'],
                'url' => $result['url'],
            ],
        ]);

        return $this->responseCreated();
    }

    public function destroy(int $id, WeChatOfficialAccountService $weChatOfficialAccountService): JsonResponse
    {
        $row = $this->repository->getById($id);
        $api = $weChatOfficialAccountService->getClient();
        $response = $api->postJson('cgi-bin/material/del_material', [
            'media_id' => $row['media_id'],
        ]);
        if ($response->isSuccessful()) {
            $row->delete();
        } else {
            abort(403, $response->toArray(true));
        }

        return $this->responseDeleted();
    }
}
